import { useMemo } from 'react';
import { useLocation } from 'react-router';
import { useTaskDetail } from 'utils/task';
import { useSetSearchUrlParam, useUrlQueryParam } from 'utils/useUrlQueryParam';
import { useProjectDetail } from '../../utils/project';

export const useProjectIdInUrl = () => {
    const { pathname } = useLocation();
    const id = pathname.match(/projects\/(\d+)/)?.[1]
    return Number(id);
}

export const useProjectInUrl = () => useProjectDetail(useProjectIdInUrl())

// 统一用param的方式查询看板和task

export const useKanbanSearchParams = () => ({ projectId: useProjectIdInUrl() })
export const useKanbansQueryKey = () => ["kanbans", useKanbanSearchParams()];

export const useTaskSearchParams = () => {
    const projectId = useProjectIdInUrl();
    const [param, setParam] = useUrlQueryParam([
        "name",
        "typeId",
        "processorId",
        "tagId"
    ]);
    return useMemo(
        () => ({
            projectId,
            typeId: Number(param.typeId) || undefined,
            processorId: Number(param.processorId) || undefined,
            tagId: Number(param.tagId) || undefined,
            name: param.name
        }),
        [projectId, param]
    )
};
export const useTasksQueryKey = () => ["tasks", useTaskSearchParams()];

// 看板弹框
export const useTaskModal = () => {
    const [{ taskCreate }, setTaskCreate] = useUrlQueryParam(['taskCreate']);
    const [{ editingTaskId }, setEditingTaskId] = useUrlQueryParam(['editingTaskId']);
    const { data: editingTask, isLoading } = useTaskDetail((Number(editingTaskId)))

    const setSearchParams = useSetSearchUrlParam();

    const open = () => {
        setTaskCreate({ taskCreate: true })
    }

    const close = () => setSearchParams({ taskCreate: "", editingTaskId: "" });

    const startEdit = (id: number) => {
        setEditingTaskId({ editingTaskId: id })
    }

    return {
        taskModalOpen: taskCreate === 'true' || Boolean(editingTaskId),
        open,
        close,
        startEdit,
        editingTask,
        editingTaskId,
        isLoading
    }
}
